package cn.gailvlun.gll.presentation.profile;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.blankj.utilcode.util.KeyboardUtils;

import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import cn.gailvlun.gll.R;
import cn.gailvlun.gll.chatkit.ChatKitBindingAdapter;
import cn.gailvlun.gll.databinding.ActivityCompleteInfoBinding;
import cn.gailvlun.gll.net.HttpMethods;
import cn.gailvlun.gll.net.HttpSubscriber;
import cn.gailvlun.gll.net.base.GetAvatarRes;
import cn.gailvlun.gll.net.base.Profile;
import cn.gailvlun.gll.net.base.profile.AddProfileReq;
import cn.gailvlun.gll.presentation.base.BaseActivity;
import cn.gailvlun.gll.presentation.login.SelectHeaderActivity;
import cn.gailvlun.gll.presentation.login.adapter.GenderType;
import cn.gailvlun.gll.util.DateUtil;
import cn.gailvlun.gll.util.DialogUtil;
import cn.gailvlun.gll.util.ProfileUtil;
import cn.gailvlun.gll.util.RxUtil;
import cn.gailvlun.gll.util.ToastUtil;
import cn.gailvlun.gll.widget.NavigationBarView;
import io.reactivex.functions.Consumer;
import rx_activity_result2.Result;



public class CompleteInfoActivity extends BaseActivity {

    public static void openActivity(Context context) {
        Intent intent = new Intent(context, CompleteInfoActivity.class);
        context.startActivity(intent);
    }

    private ActivityCompleteInfoBinding mBinding;
    private GetAvatarRes selectedAvatarRes;

    @Override
    protected void initComponent() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_complete_info);
        mBinding.setPresenter(new Presenter());
    }

    @Override
    protected void createHandler() {
        mBinding.nbv.setOnBackListener(new NavigationBarView.OnBackListener() {
            @Override
            public void onBack(NavigationBarView nb) {
                onBackPressed();
            }
        });
        mBinding.nbv.setOnMenuClickListener(new NavigationBarView.OnMenuClickListener() {
            @Override
            public void onMenuClick(NavigationBarView nb) {
                AddProfileReq addProfileReq = new AddProfileReq();
                addProfileReq.setAvatar(selectedAvatarRes == null ? null : mProfile.getAvatar());
                addProfileReq.setName(mProfile.getName());
                addProfileReq.setDescription(mProfile.getDescription());
                if (mBinding.getBirthday() != null) {
                    addProfileReq.setBirthday(DateUtil.toBirthday(mBinding.getBirthday()));
                }

                addProfileReq.setGender(mBinding.getGenderType() != GenderType.female);
                addProfileReq.setIs_profile_public(mBinding.st.isChecked());
                HttpMethods.getProfileService().modifyProfile(addProfileReq)
                        .compose(RxUtil.<Profile>applyScheduler())
                        .subscribe(new HttpSubscriber<Profile>() {
                            @Override
                            protected void onSuccess(Profile response) {
                                ProfileUtil.modify(response);
                                ToastUtil.showShort("保存成功");
                            }

                            @Override
                            protected void onFailure(String errMsg, @Nullable Profile response, int code) {
                                DialogUtil.showError(mContext, errMsg);
                            }
                        });
            }
        });
    }

    private Profile mProfile;

    @Override
    protected void loadData(@Nullable Bundle savedInstanceState) {
        Profile tempProfile = ProfileUtil.getProfile();

        if (mProfile == null && tempProfile != null) {
            mProfile = new Profile();
            mProfile.setAvatar(tempProfile.getAvatar());
            mProfile.setName(tempProfile.getName());
            mProfile.setGaiid(tempProfile.getGaiid());
            mProfile.setDescription(tempProfile.getDescription());
            mProfile.setGender(tempProfile.isGender());
            mProfile.setBirthday(tempProfile.getBirthday());
            mProfile.setCity(tempProfile.getCity());
            mProfile.setIs_profile_public(tempProfile.getIs_profile_public());
        }

        mBinding.setProfile(mProfile);

        mBinding.setGenderType(GenderType.getGenderByBoolean(mProfile.isGender()));
        if (mProfile.getBirthday() != null) {
            mBinding.setBirthday(DateUtil.toCalendar(
                    DateUtil.parse(DateUtil.DATE_PATTERN, mProfile.getBirthday())
            ));
        }
    }

    public class Presenter {
        public void onAvatar() {
            SelectHeaderActivity.openActivityForResult(mContext)
                    .subscribe(new Consumer<Result<Activity>>() {
                        @Override
                        public void accept(Result<Activity> activityResult) throws Exception {
                            if (activityResult.resultCode() == RESULT_OK
                                    && activityResult.data() != null) {
                                selectedAvatarRes = (GetAvatarRes) activityResult.data().getSerializableExtra("data");
                                ChatKitBindingAdapter.loadHeader(mBinding.rivAvatar, selectedAvatarRes.getTrust_url());
                                mProfile.setAvatar(selectedAvatarRes.getFile_name());
                            }
                        }
                    });
        }

        public void onGender(GenderType genderType) {
            KeyboardUtils.hideSoftInput(mContext);
            final List<GenderType> genderList = Arrays.asList(GenderType.values());
            OptionsPickerView<GenderType> pickerView = new OptionsPickerView.Builder(mContext,
                    new OptionsPickerView.OnOptionsSelectListener() {
                        @Override
                        public void onOptionsSelect(int options1, int options2, int options3, View v) {

                            GenderType selectGender = genderList.get(options1);
                            mBinding.setGenderType(selectGender);
                        }
                    }).build();
            pickerView.setPicker(genderList);
            if (genderType != null) {
                pickerView.setSelectOptions(genderType.ordinal());
            }
            pickerView.show();
        }

        public void onBirthday(Calendar selectedDate) {
            KeyboardUtils.hideSoftInput(mContext);
            TimePickerView pvTime = new TimePickerView.Builder(mContext, new TimePickerView.OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {
                    mBinding.setBirthday(DateUtil.toCalendar(date));
                }
            })
                    .setType(new boolean[]{true, true, true, false, false, false})
                    .setLabel("年", "月", "日", null, null, null)
                    .build();
            if (selectedDate == null) {
                pvTime.setDate(Calendar.getInstance());
            } else {
                pvTime.setDate(selectedDate);
            }
            pvTime.show();
        }
    }

    public static class Util {
        public static String getBirthday(Calendar calendar) {
            if (calendar == null) {
                return null;
            }
            return DateUtil.format(DateUtil.DATE_PATTERN, calendar.getTime());
        }
    }
}
